package com.margo.project.redis.script.action;

import java.util.LinkedList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * redis 投票
 * @author fangxingbang
 *
 */
@RestController
public class RedisChoiceController {
	
	@Autowired
	private StringRedisTemplate stringRedisTemplate;
	
	/**
	 * localhost:8080/redis/choice/fxb/A
	 * localhost:8080/redis/choice/margo/A
	 * localhost:8080/redis/choice/SuperAdmin/B
	 * localhost:8080/redis/choice/heyan/C
	 * @param projectId
	 * @return
	 * @throws InterruptedException
	 */
	@RequestMapping(path="/redis/choice/{userId}/{choice}")
	private String script(@PathVariable String userId,@PathVariable String choice) throws InterruptedException {
		List<String> keys=new LinkedList<String>();
		keys.add("welfare:20210406:user");
		if("A".equals(choice)) {
			keys.add("welfare:20210406:A");
		}else if("B".equals(choice)) {
			keys.add("welfare:20210406:B");
		}else if("C".equals(choice)) {
			keys.add("welfare:20210406:C");
		}else {
			keys.add("welfare:20210406:D");
		}
		DefaultRedisScript<Long> script=new DefaultRedisScript<Long>("if(redis.call('sismember',KEYS[1],ARGV[1])==1) then \r\n" + 
				"	return 1; \r\n" + 
				"else \r\n" + 
				"	redis.call('sadd',KEYS[1],ARGV[1]); \r\n" + 
				"	redis.call('incr',KEYS[2]); \r\n" + 
				"end; \r\n" + 
				"return 2;",Long.class);
		script.setResultType(Long.class);
		Object result=(Object) stringRedisTemplate.execute(script, keys, userId);
		return result.toString();
	}
}
